package com.yun.zf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.common.admin.domain.SysAgent;
import com.yun.zf.common.admin.domain.SysDept;
import com.yun.zf.common.admin.domain.SysUserRole;
import com.yun.zf.common.admin.dto.community.AgentInfoDto;
import com.yun.zf.common.admin.dto.sys.PostListDto;
import com.yun.zf.common.admin.dto.sys.RoleListDto;
import com.yun.zf.common.admin.model.SysAgentEditMo;
import com.yun.zf.common.admin.model.sys.AgentAddMo;
import com.yun.zf.common.admin.model.sys.AgentBasicMo;
import com.yun.zf.common.admin.model.sys.AgentEditMo;
import com.yun.zf.common.admin.model.sys.AgentSearchMo;
import com.yun.zf.common.app.domain.ZfCity;
import com.yun.zf.common.mapstruct.admin.AgentMapper;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.mapper.SysAgentMapper;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.service.*;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Log
public class SysAgentServiceImpl extends ServiceImpl<SysAgentMapper, SysAgent> implements SysAgentService {

    @Autowired
    private SysAgentMapper sysagentMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private SysPostService postService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ZfCityService cityService;

    @Override
    public Page<SysAgent> getAgentList(AgentSearchMo searchMo) {
        Page<SysAgent> page = new Page<>(searchMo.getCurrent(), searchMo.getPageSize());
        List<SysAgent> agentMoList = sysagentMapper.getAgent(searchMo, page);
        page.setRecords(agentMoList);

        return page;
    }

    @Override
    public List<SysAgent> hasAgent(long deptId) {
        QueryWrapper<SysAgent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.lambda().eq(SysAgent::getDeptId, deptId);
        List<SysAgent> agentList = baseMapper.selectList(agentQueryWrapper);
        return agentList;
    }

    @Override
    public SysAgentEditMo getEditInfo() {
        // 获取角色信息
        List<RoleListDto> roleList = roleService.getAllRoles();
        //获取岗位信息
        List<PostListDto> posts = postService.getPosts();
        SysAgentEditMo editMo = new SysAgentEditMo();
        editMo.setPosts(posts);
        // editMo.setTreeList(treeList);
        editMo.setRoleList(roleList);
        return editMo;
    }

    /**
     * 修改经济人信息
     *
     * @param
     * @return
     */
    @Override
    @Transactional
    public Boolean motifyAgent(AgentEditMo editMo, SysAgent agent) {

        agent.setModifiedTime(new Date());
        agent.setCardNo(editMo.getCardNo());
        agent.setName(editMo.getName());
        agent.setIphone(editMo.getIphone());
        agent.setStatus(editMo.getStatus());
        agent.setRemarks(editMo.getRemarks());
        agent.setEmail(editMo.getEmail());
        agent.setPostId(editMo.getPostId());
        QueryWrapper<SysAgent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.lambda().eq(SysAgent::getId, agent.getId())
                .eq(SysAgent::getUserId, agent.getUserId());

        baseMapper.update(agent, agentQueryWrapper);
        boolean flage = true;
        // 删除角色信息重新插入
        userRoleService.delRolesByUserId(editMo.getUserId());
        if (editMo.getRoleIds() != null && editMo.getRoleIds().length > 0) {
            List<SysUserRole> userRoleList = new ArrayList<>();
            for (Long roleId : editMo.getRoleIds()
            ) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(editMo.getUserId());
                userRole.setRoleId(roleId);
                userRoleList.add(userRole);
            }
            // 批量添加用户角色
            flage = userRoleService.batchList(userRoleList);
        }
        return flage;
    }


    @Override
    @Transactional
    public int addAgentAny(AgentAddMo agentMo, Long userId) {
        SysAgent agent = AgentMapper.INSTANCE.agentAddMotoDomain(agentMo);
        agent.setCreateTime(new Date());
        agent.setModifiedTime(new Date());
        agent.setUserId(userId);
        // 工号根据当前城市，初始默认值为10000，如果存在则取最大+1
        // 获取当前城市最大的工号
        int curAgentNo = this.maxAgentNo(agent.getCityCode());
        if (curAgentNo <= 0) {
            agent.setAgentNo(10000);
        } else {
            agent.setAgentNo(curAgentNo + 1);
        }
        //获取部门级联
       String[] deptIds = agentMo.getDept();
        if (deptIds.length == 1) {
            agent.setDeptId(Long.parseLong(deptIds[0]));
        } else if (deptIds.length  == 2) {
            agent.setDeptId(Long.parseLong(deptIds[1]));
        }
        // 存储选择数组
        agent.setDeptIds(JSONObject.toJSONString(deptIds));
        // 获取部门名称
        SysDept dept = deptService.getDeptByDeptId(agent.getDeptId());
        agent.setDeptName(dept.getDeptName());

        if (agentMo.getCity() == null || agentMo.getCity().length < 2) {
            throw new CustomException("请确认是否选择城市");
        }
        // 获取城市名称
        ZfCity city = cityService.getCity(Long.parseLong(agentMo.getCity()[1]));
        agent.setCityCode(Long.parseLong(agentMo.getCity()[1]));
        agent.setProvinceCode(city.getOneLevel());
        agent.setProvinceName(city.getOneLevelName());
        agent.setCityName(city.getCityName());

        //新增经纪人信息
        int count = baseMapper.insert(agent);
        List<SysUserRole> userRoleList = new ArrayList<>();
        if (count > 0 && agentMo.getRoleIds() != null && agentMo.getRoleIds().length > 0) {
            for (Long roleId : agentMo.getRoleIds()
            ) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleList.add(userRole);
            }
            // 批量添加用户角色
            userRoleService.batchList(userRoleList);
        }

        return count;
    }


    @Override
    public SysAgent checkUniAgent(String cardNo, String iphone) {
        QueryWrapper<SysAgent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.lambda().eq(SysAgent::getCardNo, cardNo).or().eq(SysAgent::getIphone, iphone);
        return baseMapper.selectOne(agentQueryWrapper);
    }

    @Override
    public void motifyAgentById(Long id) {
        sysagentMapper.motifyAgentById(id);
    }

    @Override
    public SysAgent getInfoByUserId(Long userId) {
        QueryWrapper<SysAgent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.lambda().eq(SysAgent::getStatus, 0).eq(SysAgent::getDelFlag, 0)
                .eq(SysAgent::getUserId, userId);
        return baseMapper.selectOne(agentQueryWrapper);
    }

    @Override
    public SysAgent getAgent(Long userId, int id) {
        QueryWrapper<SysAgent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.lambda().eq(SysAgent::getId, id)
                .eq(SysAgent::getUserId, userId);
        return baseMapper.selectOne(agentQueryWrapper);

    }

    @Override
    public AgentInfoDto getAgentByNo(int agentNo, Long cityCode) {
        return baseMapper.getAgentInfo(agentNo, cityCode);
    }

    @Override
    public List<AgentInfoDto> getAgentByCommunityId(Long communityId) {
        return baseMapper.getAgentByCommunityId(communityId);
    }

    @Override
    public int maxAgentNo(Long cityCode) {

        String maxNo = baseMapper.getMaxAgentNo(cityCode);
        return maxNo == null ? 0 : Integer.parseInt(maxNo);
    }

    @Override
    public int checkIsDelFlag(int agentId) {
        QueryWrapper<SysAgent> agentQueryWrapper = new QueryWrapper<>();
        agentQueryWrapper.lambda().eq(SysAgent::getDelFlag, 0).eq(SysAgent::getId, agentId);
        return baseMapper.selectCount(agentQueryWrapper);
    }

    @Override
    public void changeStatus(int agentId, int status) {
        baseMapper.changeStatus(agentId, status);
    }

    @Override
    public int editUser(AgentBasicMo agentMo) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        QueryWrapper<SysAgent> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysAgent::getUserId,userId);
       SysAgent agent = baseMapper.selectOne( wrapper);
        BeanUtil.copyProperties(agentMo, agent,  CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
      return     baseMapper.update(agent,wrapper);
    }

    @Override
    public AgentBasicMo getUserBasic() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        QueryWrapper<SysAgent> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysAgent::getUserId,userId);
        SysAgent agent = baseMapper.selectOne( wrapper);
       return   AgentMapper.INSTANCE.agentToMo(agent);
    }
}
